package Util;

import java.util.ArrayList;
import java.util.List;

/**
 * Miscellaneous utility methods.
 */
public class MiscUtil
{
	/**
	 * Returns a 'safe' string, i.e. the string itself, or an empty string if null is provided.
	 * The return value is guaranteed to be not-null.
	 * 
	 * @param s The string to return safely
	 * @return The string itself, or an empty string if null was provided
	 */
	public static String safeString(String s)
	{
		if (s == null)
			return "";
		
		return s;
	}
	
	/**
	 * Returns a 'safe' list, i.e. the list itself, or an empty list if null is provided.
	 * The return value is guaranteed to be not-null.
	 * 
	 * @param l The list to return safely
	 * @return The list itself, or an empty list if null was provided
	 */
	public static <T> List<T> safeList(List<T> l)
	{
		if (l == null)
			return new ArrayList<T>();
		
		return l;
	}
	
	/**
	 * Aggregates the given list of items into one comma separated string.
	 * 
	 * @param <T> Any type. toString() will be used for string representation.
	 * @param items The list of items to concatenate.
	 * @return A comma separated string of the string representations of the items
	 */
	public static <T> String aggregateToString(List<T> items)
	{
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < items.size(); i++)
		{
			String s = items.get(i).toString();
			
			sb.append(s);
			if (i < items.size() - 1)
				sb.append(", ");
		}
		
		return sb.toString();
	}
}
